package cx.crypto.android.DroidPass;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import org.bouncycastle.crypto.digests.SHA256Digest;
import org.bouncycastle.util.encoders.Hex;

public class DroidPass extends Activity
						implements View.OnClickListener {

	private EditText pass1;
	private EditText pass2;
	private Button setPassBtn;
	private TextView tvDigest;
	
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.welcome);
        
        pass1 = (EditText) findViewById(R.id.password);
        pass2 = (EditText) findViewById(R.id.password_confirmation);
        tvDigest = (TextView) findViewById(R.id.digest);
        
        setPassBtn = (Button) findViewById(R.id.set_pass);
        setPassBtn.setOnClickListener(this);
        
    }
    
    public void onClick(View view) {
    	
    	// Hide the virtual keyboard
    	InputMethodManager imm = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);
    	imm.hideSoftInputFromWindow(setPassBtn.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
    	
    	// Retrieve passwords from EditTexts
    	String str1 = pass1.getText().toString();
    	String str2 = pass2.getText().toString();
    	
    	// Make sure the password is not empty
    	if (str1.length() == 0) {
    		Toast.makeText(this, R.string.err_tooshort, Toast.LENGTH_SHORT).show();
    		return;
    	}
    	
    	// Make sure the passwords match
    	if (str1.equals(str2)) {
    		// TODO replace with hash/key generation
    		SHA256Digest sha = new SHA256Digest();
    		byte[] digest = new byte[sha.getDigestSize()];
    		sha.update(str1.getBytes(), 0, str1.getBytes().length);
    		sha.doFinal(digest, 0);
    		tvDigest.setText(new String(Hex.encode(digest)));
    	} else {
    		Toast.makeText(this, R.string.err_mismatch, Toast.LENGTH_SHORT).show();
    		return;
    	}
    }
}